package com.zhibo.controller;

import com.zhibo.util.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.solar.bean.JsonResult;
import org.solar.cache.Cache;
import org.solar.coder.AESCoder;
import org.solar.util.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@Controller
public class CaptchaController {
    private static final Logger logger = LoggerFactory.getLogger(CaptchaController.class);
    AESCoder aesCoder = new AESCoder(Config.aesPassword);
    static {
        AliMessageSender.accessKeyId= PropertiesUtil.getValueByKey("ali_Msg_accessKeyId", "config.txt");
        AliMessageSender.accessSecret= PropertiesUtil.getValueByKey("ali_Msg_accessSecret", "config.txt");
    }

    @RequestMapping("captcha")
    public String captcha(HttpSession session,HttpServletResponse hres) throws Exception {
        Captcha captcha=new Captcha();
        String code=captcha.randomString();
        session.setAttribute("imgCode",code);
        byte[] img=captcha.generateCaptchaImage(code);
        OutputStream os=hres.getOutputStream();
        os.write(img);
        os.close();
        return null;

    }
    @RequestMapping("sendMsgCode")
    @ResponseBody
    public JsonResult sendMsgCode(HttpSession session,String imgCode,String mobileNo) throws Exception {
        String mobileNoCode="1234";//new Random().nextInt(9000)+1000+"";
        //不强制必须图片验证码
        if (StringUtil.isNotEmpty(imgCode)){
            String sessionImgCode=(String) session.getAttribute("imgCode");
            if (!imgCode.equalsIgnoreCase(sessionImgCode)){
                return JsonResult.error("图片验证码错误!");
            }
        }
        System.out.println(mobileNo+"mobileNoCode="+mobileNoCode);
        Cache.getDefaultCache().put("mobileNoCode:"+mobileNo,mobileNoCode,1000*60*30);
        Map codeMap=new HashMap();
        codeMap.put("code",mobileNoCode);
//        if (mobileNo.length()<10){
//            return JsonResult.success("发送成功!");
//        }
        String result=AliMessageSender.sendMsg("河对面","SMS_105860017",mobileNo,JsonUtil.toJSONString(codeMap));
//        System.out.println(result);
        return JsonResult.success("发送成功!");
    }



}
